import { Body, Controller, Logger, Post, Req, Res } from '@nestjs/common';
import { Request,Response} from 'express';
import { EmailService } from 'src/service/email/email.service';
import { MailEntity, ResultBean } from 'src/types';
import { CodeGenerator } from 'src/utils';

@Controller('/sv')
export class EmailController {

    private readonly logger: Logger = new Logger(EmailController.name);

    constructor(
        private readonly emailService: EmailService
    ) { }


    @Post("/sendEmail")
    async sendEmail(@Body() entity: MailEntity, @Req() req:Request, @Res() res:Response) {

        let emails = (req as any).session.emails;


        let vcode = CodeGenerator.generateNumOf(6);

        emails[entity.email] = vcode;

        this.emailService.sendMail(entity.email, vcode).then(() => {
            this.logger.log(`发送成功,email=${entity.email}验证码为：${vcode}`);
        }).catch(err => {
            this.logger.error(`发送失败,email=${entity.email}验证码为：${vcode}`);
        })


        const result = ResultBean.builder({
            code: "200",
            msg: "发送成功"
        })


        res.json(result);
    }
}
